package net.forsuber.schedule;

import net.forsuber.data.DataSource;
import net.forsuber.data.DataSourceException;
import net.forsuber.data.Record;
import net.forsuber.publish.Publisher;
import net.forsuber.publish.PublisherException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.prefs.Preferences;

/**
 * User: lzap
 * Date: 27.7.2007
 * Time: 22:51:09
 */
public class ContinuousScheduler implements Scheduler {

    private static final Log LOG = LogFactory.getLog(ContinuousScheduler.class);

    private DataSource dataSource;

    private Publisher publisher;

    private int repeat = 1;

    private int initialValue = 0;

    private Preferences preferences;

    public void init(Preferences prefs) {
        this.preferences = prefs;
    }

    public void run() throws SchedulerException {
        try {
            dataSource.open();
            int last = preferences.getInt("ContinuousSchedulerLastRecord", getInitialValue());
            for (int i = 0; i < repeat; i++) {
                Record record = dataSource.getRecord(last++);
                publisher.open();
                LOG.info("Publishing record number " + last);
                publisher.publish(record);
            }
            preferences.putInt("ContinuousSchedulerLastRecord", last);
        } catch (PublisherException e) {
            throw new SchedulerException(e);
        } catch (DataSourceException e) {
            throw new SchedulerException(e);
        } finally {
            try {
                dataSource.close();
            } catch (DataSourceException e) {
                // we dont care
            }
            publisher.close();
        }
    }

    public void destroy() {
    }

    public int getRepeat() {
        return repeat;
    }

    public void setRepeat(int repeat) {
        this.repeat = repeat;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    public int getInitialValue() {
        return initialValue;
    }

    public void setInitialValue(int initialValue) {
        this.initialValue = initialValue;
    }
}
